package com.bungarus.bridge.busi;

import com.bungarus.bridge.BusiBridge;
import com.bungarus.busi.InnerClient;
import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.MessageBuilder;
import com.bungarus.model.MessageType;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created by tang on 2018/12/30.
 */
@ChannelHandler.Sharable
public class TransferMsgForProcessingLargeGroupHandler extends ChannelInboundHandlerAdapter {
    Logger logger = Logger.getLogger(TransferMsgForProcessingLargeGroupHandler.class);
    private final BusiBridge busiBridge;

    public TransferMsgForProcessingLargeGroupHandler(BusiBridge busiBridge) {
        this.busiBridge = busiBridge;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof MessageProtobuf.Message) {
            MessageProtobuf.Message largeGroupMsg = (MessageProtobuf.Message) msg;
            switch(largeGroupMsg.getHeader().getType()){
                case MessageType.HEARTBEAT_PING:
                    //send back pong
                    ctx.writeAndFlush(MessageBuilder.buildHeartbeatPongMessage(largeGroupMsg.getHeader().getId(), largeGroupMsg.getHeader().getId2()));
                    break;
                case MessageType.IM_GROUP:
                    logger.info("++++++++++ Message received : \n" + largeGroupMsg.toString());
                    List<InnerClient> largeGroupMsgProcessors = this.busiBridge.getInnerClientList().get(BusiBridge.CLUSTER_TAG_BUSI);
                    if (largeGroupMsgProcessors.size() > 0) {
                        InnerClient largeGroupProcessor;
                        do {
                            int index = Integer.parseInt(largeGroupMsg.getHeader().getId()) % largeGroupMsgProcessors.size();
                            largeGroupProcessor = largeGroupMsgProcessors.get(index);
                        } while (largeGroupProcessor.isShuttingDown());
                        largeGroupProcessor.sendMessage(
                                MessageBuilder.buildProcessLargeGroupMsg(largeGroupMsg, BusiBridge.CLUSTER_TAG_BUSI),
                                BusiBridge.CLUSTER_TAG_BUSI, ctx);
                    }
                    break;
                case MessageType.ROUTE_SPAN_CLUSTERS:
                case MessageType.ROUTE_SPAN_AZ:
                case MessageType.ROUTE_SPAN_REGION:
                    //todo: route span
                    break;
                default:
                    break;
            }
        }
        else {
            super.channelRead(ctx, msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
